package cn.niit.smbms.controller.api;

import cn.niit.smbms.entity.News;
import cn.niit.smbms.model.reponse.BaseResponse;
import cn.niit.smbms.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 新闻管理控制器
 * @author xiaomi
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 搜索查询新闻列表
     * @param title
     * @return
     */
    //@CrossOrigin(value = "http://127.0.0.1:81",maxAge = 1800,allowedHeaders = "*")
    @GetMapping("/news")
    public BaseResponse<List<News>> newsList(@RequestParam(name = "title", defaultValue = "") String title){
        News news = new News();
        news.setTitle(title);
        return new BaseResponse<>(newsService.selectNewsList(news));
    }

    @PostMapping("/news")
    public BaseResponse<List<News>> addNews(@RequestBody News news){
        log.info("添加新闻：{}", news);
        int rows = newsService.insertNews(news);
        if(rows > 0){
            return new BaseResponse<>("添加成功！");
        }
        return new BaseResponse<>("100001", "添加失败");
    }

    @PutMapping("/news")
    public BaseResponse<List<News>> updateNews(@RequestBody News news){
        log.info("更新新闻：{}", news);
        if(null != news && null != news.getId() && news.getId() > 0){
            int rows = newsService.updateNews(news);
            if(rows > 0){
                return new BaseResponse<>("更新成功！");
            }
            return new BaseResponse<>("100002", "更新失败");
        }
        return new BaseResponse<>("000001", "更新失败，请求数据不能为空！");
    }

    @DeleteMapping("/news/{id}")
    public BaseResponse<List<News>> deleteNews(@PathVariable("id") Long newsId){
        log.info("删除新闻：{}", newsId);
        int rows = newsService.deleteNews(newsId);
        if(rows > 0){
            return new BaseResponse<>("删除成功！");
        }
        return new BaseResponse<>("100003", "删除失败");
    }
}